package com.zlzlib.liblayoutmanager;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @Desc: 翻页效果工具类
 * @Copyright:
 * @DateTime: 2021/8/19 11:16
 * @Author zlz
 * @Version 1.0
 */
public class PageSnapUtils extends CenterSnapUtils{

    @Override
    public boolean onFling(int velocityX, int velocityY) {
        BaseLayoutManager layoutManager = (BaseLayoutManager) mRecyclerView.getLayoutManager();
        if (layoutManager == null) {
            return false;
        }
        RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
        if (adapter == null) {
            return false;
        }
        if (!layoutManager.isInfiniteLoop() && (layoutManager.mOffset == layoutManager.getMaxOffset()
                        || layoutManager.mOffset == layoutManager.getMinOffset())) {
            return false;
        }
        final int minFlingVelocity = mRecyclerView.getMinFlingVelocity();
        mGravityScroller.fling(0, 0, velocityX, velocityY,
                Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
        if (layoutManager.mOrientation == BaseLayoutManager.VERTICAL && Math.abs(velocityY) > minFlingVelocity) {
            final int currentPosition = layoutManager.getCurrentPositionOffset();
            final int offsetPosition = mGravityScroller.getFinalY() * layoutManager.getDistanceRatio() > layoutManager.mInterval ? 1 : 0;
            ScrollUtils.smoothScrollToPosition(mRecyclerView, layoutManager, layoutManager.getReverseLayout() ?
                    -currentPosition - offsetPosition : currentPosition + offsetPosition);
            return true;
        } else if (layoutManager.mOrientation == BaseLayoutManager.HORIZONTAL && Math.abs(velocityX) > minFlingVelocity) {
            final int currentPosition = layoutManager.getCurrentPositionOffset();
            final int offsetPosition = mGravityScroller.getFinalX() * layoutManager.getDistanceRatio() > layoutManager.mInterval ? 1 : 0;
            ScrollUtils.smoothScrollToPosition(mRecyclerView, layoutManager, layoutManager.getReverseLayout() ?
                    -currentPosition - offsetPosition : currentPosition + offsetPosition);
            return true;
        }
        return true;
    }
}
